<template>
  <div class="app-main-container">
    <QueryForm v-model="filters" :query-form-config="queryFormConfig" @handleQuery="getListByFilters" @clear="clearFilters" />
    <div v-if="meta.indexOf('RoleAdd') > -1" class="doumee-table-buttons">
      <!-- <el-button v-if="buttons.add" type="primary" @click="toVipCardAdd">{{translate('zj')}}</el-button> -->
      <el-button v-preventReClick type="primary" @click="toVipCardAdd">{{
        translate("add")
      }}</el-button>
    </div>
    <el-table ref="table" :data="list" element-loading-text="Loading" border fit :header-row-class-name="'table-header'" class="doumee-element-table">
      <el-table-column align="center" :label="translate('careerId')" prop="id" min-width="200" fixed="left" />
      <el-table-column align="center" :label="translate('careerName')" prop="name" min-width="140" />
      <el-table-column align="center" :label="translate('careerType')" min-width="140">
        <template slot-scope="scope">
          <span v-if="scope.row.type == 0">{{ translate("pingtai") }}</span>
          <span v-if="scope.row.type == 1">{{ translate("shop") }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="translate('careerDesc')" prop="info" min-width="300" />
      <el-table-column :label="translate('handle')" :width="$i18n.locale === 'ZH'? 240 : 340" align="center" fixed="right">
        <template slot-scope="scope">
          <div v-if="scope.row.type == 1" class="flex-cc">
            <el-button v-if="meta.indexOf('RoleEdit') > -1" v-preventReClick type="text" @click="toEdit(scope.row)">{{ translate("edit") }}</el-button>
            <el-button v-if="meta.indexOf('RoleEdit') > -1" v-preventReClick type="text" @click="toBindRoleMenuList(scope.row.id)">{{ translate("fpqx") }}</el-button>
            <el-button v-if="meta.indexOf('RoleDel') > -1" v-preventReClick type="text" style="color: red" @click="toDelete(scope.row.id)">{{ translate("del") }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex-cc doumee-pagination">
      <el-pagination background layout="prev, pager, next" :total="total" hide-on-single-page @current-change="currentChange" />
    </div>

    <el-dialog :close-on-click-modal="modalDialog" :lose-on-press-escape="modalDialog" :title="translate('roleAdd')" :visible.sync="showAddRole">
      <el-form ref="addForm" :rules="rules" :model="newRoleData" label-width="auto">
        <el-form-item :label="translate('careerName')" prop="name">
          <el-input v-model="newRoleData.name" :placeholder="translate('careerNamePlace')" />
        </el-form-item>
        <el-form-item :label="translate('careerDesc')">
          <el-input v-model="newRoleData.info" :placeholder="translate('careerDescP')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddRole = false">{{
          translate("cancel")
        }}</el-button>
        <el-button v-preventReClick :loading="subLoading" type="primary" @click="comfirmAddNewRole">{{ translate("enter") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="modalDialog" :lose-on-press-escape="modalDialog" :title="translate('roleEdit')" :visible.sync="showEditRole">
      <el-form ref="editForm" :rules="rules" :model="editRoleData" label-width="auto">
        <el-form-item :label="translate('careerName')" prop="name">
          <el-input v-model="editRoleData.name" :placeholder="translate('careerNamePlace')" />
        </el-form-item>
        <el-form-item :label="translate('careerDesc')">
          <el-input v-model="editRoleData.info" :placeholder="translate('careerDescP')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEditRole = false">{{
          translate("cancel")
        }}</el-button>
        <el-button v-preventReClick :loading="subLoading" type="primary" @click="comfirmEditRole">{{ translate("enter") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { roleList, addRole, editRole, deleteRole } from '@/api'
import { queryFormConfig } from './config'
export default {
  name: 'RoleList',
  data () {
    return {
      modalDialog: this.$store.state.app.dialog,
      queryFormConfig,
      subLoading: false,
      meta: [],
      buttons: {},
      list: [],
      pagination: {
        page: 1,
        rows: 10,
        firstQueryTime: new Date()
      },
      total: 0,
      marketingActiveName: 'first',
      filters: {
        name: ''
      },
      showAddRole: false,
      newRoleData: {
        name: '',
        info: ''
      },
      showEditRole: false,
      editRoleData: {},
      showBindRoleMenu: false,
      activeBindRoleMenuTab: 'firstBindRoleMenuTab',
      allRoleMenu: [],
      rules: {
        name: [
          { required: true, message: this.translate('careerNamePlace'), trigger: 'blur' }
        ],
        info: [
          { required: true, message: this.translate('careerDescP'), trigger: 'blur' }
        ]
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      const buttons = to.meta.buttons
      for (const i in buttons) {
        vm.buttons[buttons[i]] = true
      }
    })
  },
  created () {
    this.meta = this.$route.meta.buttons || []
    this.getRoleList()
  },
  mounted () {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated () {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    // 获取列表
    getRoleList () {
      const { pagination, filters: param } = this
      roleList({ pagination, param }).then(res => {
        this.list = res.recordList
        this.total = res.totalCount
        const t = res.totalCount / 10
        const count = Number(t.toFixed(0)) + (t - t.toFixed(0) > 0 ? 1 : 0)
        this.total = count * 10
      })
    },
    getListByFilters () {
      this.pagination = {
        firstQueryTime: new Date(),
        page: 1,
        rows: 10
      }
      this.getRoleList()
    },
    clearFilters () {
      this.filters = { name: '' }
      this.pagination = {
        firstQueryTime: new Date(),
        page: 1,
        rows: 10
      }
      this.getRoleList()
    },
    // 切换分页
    currentChange (page) {
      this.$set(this.pagination, 'page', page)
      this.getRoleList()
    },
    // 新增
    toVipCardAdd () {
      this.showAddRole = true
      this.newRoleData = {}
    },
    // 确认新增
    comfirmAddNewRole () {
      const that = this
      const { newRoleData } = this
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.subLoading = true
          addRole({ param: { ...newRoleData } }).then(res => {
            this.subLoading = false
            if (res.errorCode === '000000') {
              that.$message.success(this.translate('addcg'))
              that.showAddRole = false
              that.getRoleList()
              that.newRoleData = {}
            }
          }).catch(() => {
            this.subLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 编辑
    toEdit (data) {
      this.showEditRole = true
      this.editRoleData = { ...data }
    },
    // 确认编辑
    comfirmEditRole () {
      const { editRoleData } = this
      const that = this
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.subLoading = true
          editRole({ param: { ...editRoleData } }).then(res => {
            this.subLoading = false
            if (res.errorCode === '000000') {
              that.$message.success(this.translate('editcg'))
              that.showEditRole = false
              that.getRoleList()
              that.editRoleData = {}
            }
          }, () => {
            this.subLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      }).catch(() => {
        this.subLoading = false
      })
    },
    // 删除
    toDelete (id) {
      const that = this
      this.$confirm(this.translate('roleDelPlace'), this.translate('ts'), {
        confirmButtonText: this.translate('qd'),
        cancelButtonText: this.translate('cancel'),
        type: 'warning'
      }).then(() => {
        deleteRole({ param: { id } }).then(res => {
          that.$message.success(this.translate('delScs'))
          that.getRoleList()
        })
      }).catch(() => {
        this.$message.info(this.translate('canceledDel'))
      })
    },
    // 分配权限
    toBindRoleMenuList (id) {
      this.$router.push({ path: '/accountOptions/roleBind', query: { id } })
    }
  }
}
</script>
